package com.nineclock.common.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.nineclock.common.oss.config.OssClientUtils;
import com.nineclock.common.oss.config.OssProperties;
import com.nineclock.common.oss.service.OSSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@EnableConfigurationProperties(OssProperties.class)
@Import(OssClientUtils.class)
public class OSSServiceImpl implements OSSService {

    private static final String separator = "/"; //定义常量
    @Autowired
    @Lazy
    private OSSClient ossClient;

    @Autowired
    private OssProperties ossProperties;


    /**
     * 构建对象名(上传到OSS上的ObjectName)
     *
     * @param prefix
     * @param fileName yyyy/MM/dd/fileName.png
     * @return
     */
    @Override
    public String builderFilePath(String prefix, String fileName) {
        StringBuilder stringBuilder = new StringBuilder(50);
        if (!StringUtils.isEmpty(stringBuilder.toString())) {
            //前缀不为空则拼接
            stringBuilder.append(prefix).append(separator);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String currentDate = simpleDateFormat.format(new Date());

        //继续将当前日期拼接 + 文件名
        stringBuilder.append(currentDate).append(separator).append(fileName);

        return stringBuilder.toString();
    }


    /**
     * 上传图片
     *
     * @param prefix
     * @param fileName
     * @param inputStream
     * @return
     */
    @Override
    public String uploadImgFile(String prefix, String fileName, InputStream inputStream) {
        //创建objectName
        String objectName = builderFilePath(prefix, fileName);

        //上传文件到阿里云
        ossClient.putObject(ossProperties.getBucketName(), objectName, inputStream);

        //上传成功后获取访问url  文件URL的格式为https://BucketName.Endpoint/ObjectName
        //String hostStr = ossProperties.getHost(); //获取host的原始url
        //String addBucketUrl = hostStr.replace("%s", ossProperties.getBucketName()); //替换host中url的%s为BucketName
        String addBucketUrl = String.format(ossProperties.getHost(), ossProperties.getBucketName());
        StringBuilder urlPath = new StringBuilder(addBucketUrl);
        urlPath.append(objectName); //最后拼接 加上objectName

        return urlPath.toString();
    }

}
